var wxCharts = require('../../../utils/wxcharts.js');
const app = getApp();
var columnChart = null;

Page({
  data: {
    isFold: true,
    animation: {},
    letters: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'],
    chartTitle: '总成交量',
    isMainChartDisplay: true,
    windowWidth: wx.getSystemInfoSync().windowWidth,
    company:0
  },

  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中...',
    });

    if (!app.globalData.userData.openOId){
      wx.login({
        success: res => {
          wx.request({
            url: app.globalData.phpUrl + 'index/register',
            method: "POST",
            header: { 'content-type': 'application/json' },
            data: { code: res.code },
            success: function (data) {
              app.globalData.userData.openOId = data.data.data.openid;
              wx.request({
                url: app.globalData.phpUrl + 'user/api',
                method: "POST",
                header: { 'content-type': 'application/json' },
                data: { api_name: 'report', openid: data.data.data.openid, questionnaire_id: Number(options.questionnaire_id) },
                success: function (data) {
                  var da = data.data.data;
                  var l = da.question_data.length
                  for (var i = 0; i < l; i++) {
                    var qd = da.question_data
                    var ml = qd[i].options.length;
                    var all = 0;
                    for (var j = 0; j < ml; j++) {
                      all = all + qd[i].options[j].option_select;
                    };
                    da.question_data[i].anserAll = all;
                  }
                  that.setData({
                    queData: da,
                    company: da.is_company,
                  });


                  for (var ii = 0; ii < l; ii++) {
                    var max = 5;
                    var categories = [];
                    var d = [];
                    var qqd = da.question_data
                    var mll = qqd[ii].options.length;
                    for (var jj = 0; jj < mll; jj++) {
                      if (qqd[ii].type == 1 || qqd[ii].type == 2 || qqd[ii].type == 5 || qqd[ii].type == 4) {
                        categories.push(that.data.letters[jj]);
                        d.push(qqd[ii].options[jj].option_select);
                        if (qqd[ii].options[jj].option_select > 5) {
                          max = 10
                        } else if (qqd[ii].options[jj].option_select > 10) {
                          max = 20
                        } else if (qqd[ii].options[jj].option_select > 20) {
                          max = 100
                        } else if (qqd[ii].options[jj].option_select > 100) {
                          max = 500
                        } else if (qqd[ii].options[jj].option_select > 500) {
                          max = 1000
                        } else if (qqd[ii].options[jj].option_select > 1000) {
                          max = 2000
                        } else if (qqd[ii].options[jj].option_select > 2000) {
                          max = 5000
                        } else if (qqd[ii].options[jj].option_select > 5000) {
                          max = 10000
                        }
                      };
                    };
                    if (qqd[ii].type == 3) {
                      if (qqd[ii].answer) {
                        for (var jji = 0; jji < qqd[ii].answer.length; jji++) {
                          categories.push(qqd[ii].answer[jji].content);
                          d.push(qqd[ii].answer[jji].option_select);
                          if (qqd[ii].answer[jji].option_select > 5) {
                            max = 10
                          } else if (qqd[ii].answer[jji].option_select > 10) {
                            max = 20
                          } else if (qqd[ii].answer[jji].option_select > 20) {
                            max = 100
                          } else if (qqd[ii].answer[jji].option_select > 100) {
                            max = 500
                          } else if (qqd[ii].answer[jji].option_select > 500) {
                            max = 1000
                          } else if (qqd[ii].answer[jji].option_select > 1000) {
                            max = 2000
                          } else if (qqd[ii].answer[jji].option_select > 2000) {
                            max = 5000
                          } else if (qqd[ii].answer[jji].option_select > 5000) {
                            max = 10000
                          }
                        }
                      } else {
                        d = []
                      }
                    }
                    if (categories.length > 0) {
                      that.renderData(ii, categories, d, max);
                    }
                  }

                  wx.hideLoading();

                  var query = wx.createSelectorQuery();
                  query.select('#titleTxt').boundingClientRect()
                  query.exec(function (res) {
                    if (res[0].width < 250) {
                      that.setData({
                        isFold: false
                      });
                    }
                  });
                }
              });
            }
          })
        }
      });
    }else{
      wx.request({
        url: app.globalData.phpUrl + 'user/api',
        method: "POST",
        header: { 'content-type': 'application/json' },
        data: { api_name: 'report', openid: app.globalData.userData.openOId, questionnaire_id: Number(options.questionnaire_id) },
        success: function (data) {
          var da = data.data.data;
          var l = da.question_data.length
          var chartChose = []
          for (var i = 0; i < l; i++) {
            var qd = da.question_data
            var ml = qd[i].options.length;
            var all = 0;
            chartChose[i] = 1;
            for (var j = 0; j < ml; j++) {
              all = all + qd[i].options[j].option_select;
            };
            da.question_data[i].anserAll = all;
          }
          that.setData({
            chartChose: chartChose,
            queData: da,
            company: da.is_company,
          });


          for (var ii = 0; ii < l; ii++) {
            var max = 5;
            var categories = [];
            var d = [];
            var qqd = da.question_data
            var mll = qqd[ii].options.length;
            for (var jj = 0; jj < mll; jj++) {
              if (qqd[ii].type == 1 || qqd[ii].type == 2 || qqd[ii].type == 5 || qqd[ii].type == 4) {
                categories.push(that.data.letters[jj]);
                d.push(qqd[ii].options[jj].option_select);
                if (qqd[ii].options[jj].option_select > 5) {
                  max = 10
                } else if (qqd[ii].options[jj].option_select > 10) {
                  max = 20
                } else if (qqd[ii].options[jj].option_select > 20) {
                  max = 100
                } else if (qqd[ii].options[jj].option_select > 100) {
                  max = 500
                } else if (qqd[ii].options[jj].option_select > 500) {
                  max = 1000
                } else if (qqd[ii].options[jj].option_select > 1000) {
                  max = 2000
                } else if (qqd[ii].options[jj].option_select > 2000) {
                  max = 5000
                } else if (qqd[ii].options[jj].option_select > 5000) {
                  max = 10000
                }
              };
            };
            if (qqd[ii].type == 3) {
              if (qqd[ii].answer) {
                for (var jji = 0; jji < qqd[ii].answer.length; jji++) {
                  categories.push(qqd[ii].answer[jji].content);
                  d.push(qqd[ii].answer[jji].option_select);
                  if (qqd[ii].answer[jji].option_select > 5) {
                    max = 10
                  } else if (qqd[ii].answer[jji].option_select > 10) {
                    max = 20
                  } else if (qqd[ii].answer[jji].option_select > 20) {
                    max = 100
                  } else if (qqd[ii].answer[jji].option_select > 100) {
                    max = 500
                  } else if (qqd[ii].answer[jji].option_select > 500) {
                    max = 1000
                  } else if (qqd[ii].answer[jji].option_select > 1000) {
                    max = 2000
                  } else if (qqd[ii].answer[jji].option_select > 2000) {
                    max = 5000
                  } else if (qqd[ii].answer[jji].option_select > 5000) {
                    max = 10000
                  }
                }
              } else {
                d = []
              }
            }
            if (categories.length > 0) {
              console.log(categories)
              that.renderData(ii, categories, d, max);
            }
          }

          wx.hideLoading();

          var query = wx.createSelectorQuery();
          query.select('#titleTxt').boundingClientRect()
          query.exec(function (res) {
            if (res[0].width < 250) {
              that.setData({
                isFold: false
              });
            }
          });
        }
      });
    }
  },

  moreTtile: function () {
    var that = this;
    that.setData({
      isFold: false
    });
    var query = wx.createSelectorQuery();
    query.select('#moreContent').boundingClientRect();
    query.exec(function (res) {
      that.animation.bottom(- res[0].height).step({ duration: 300 });
      that.setData({
        animation: that.animation.export(),
      });
    })
  },

  defaultTtile: function () {
    var that = this;
    that.setData({
      isFold: true
    });

    that.animation.bottom('0rpx').step({ duration: 300 });
    that.setData({
      animation: that.animation.export(),
    });
  },

  renderData: function (i, categories, data, max){
    console.log(categories, data)
    var that = this;

    var column = {
      canvasId: 'columnCanvas'+i, // canvas-id
      type: 'column', // 图表类型，可选值为pie, line, column, area, ring
      categories: categories,
      series: [{ // 数据列表
        name: '票数',
        data: data,
        color: '#00bf6f'
      }],
      yAxis: {
        min: 0 // Y轴起始值
      },
      width: that.data.windowWidth - 20,
      height: 200,
      dataLabel: true, // 是否在图表中显示数据内容值
      legend: true, // 是否显示图表下方各类别的标识
      yAxis: {
        format: function (val) {
          return val + '票';
        },
        min: 0,
        max: max,
        disabled : false
      },
    };

    var seriesData = [];
    var valueAll=0;

    var maxValue = 1;
    
    for (var vv = 0; vv < data.length; vv++) {
      valueAll = valueAll + data[vv]
    };

    
    for (var vvv = 0; vvv < categories.length;vvv++){
      seriesData[vvv] = { name: categories[vvv], data: data[vvv] / valueAll};
    }
    
    function arrMax(arr){
      var max = arr[0];
      var len = arr.length;
      for (var i = 1; i < len; i++) {
        if (this[i] > max) {
          max = this[i];
        }
      };

      return max
    }

    maxValue = arrMax(maxValue)

    var pie = {
      canvasId: 'columnCanvasPie' + i,
      type: 'pie',
      series: seriesData,
      width: that.data.windowWidth - 20,
      height: 200,
      dataLabel: true,
    };
    var line = {
      canvasId: 'columnCanvasLine' + i,
      type: 'line',
      categories: categories,
      background: '#f5f5f5',
      series: [{ // 数据列表
        name: '票数',
        data: data,
        color: '#00bf6f'
      }],
      xAxis: {
        min: 0, // Y轴起始值
        disableGrid: true
      },
      yAxis: {
        format: function (val) {
          return val + '票';
        },
        min: 0,
        max: max,
        disabled: false
      },
      width: that.data.windowWidth - 20,
      height: 200,
      dataLabel: false,
      extra: {
        lineStyle: 'curve'
      }
    };
    var radar = {
      canvasId: 'columnCanvasRadar' + i,
      type: 'radar',
      categories: categories,
      series: [{
        name: '投票比例',
        data: data
      }],
      width: that.data.windowWidth - 20,
      height: 200,
      extra: {
        radar: {
          max: maxValue
        }
      }
    };

    new wxCharts(column);
    new wxCharts(pie);
    new wxCharts(line);
    new wxCharts(radar);
  },

  onReady: function (e) {
    
  },

  onShow: function () {
    var that = this;
    that.animation = wx.createAnimation({
      duration: 1000,
      transformOrigin: "100% 0",
      timingFunction: "ease",
    });

    that.setData({
      animation: that.animation.export(),
    });
  },

  onShareAppMessage: function (e) {
    var id = e.target.dataset.id;
    var msg = e.target.dataset.msg;
    var serName = '您的朋友';
    if (app.globalData.userInfo.nickName) {
      serName = app.globalData.userInfo.nickName
    };
    return {
      title: serName + '邀请你查看问卷数据报告!',
      imageUrl: '../../../images/share_data.png',
      path: 'pages/mine/dataReport/dataReport?questionnaire_id='+id
    }
  },


  answer:function(e){
    var id = e.target.dataset.id;
    wx.navigateTo({
      url: '../../reply/reply?article=true&id=' + id,
    })
  },

  choseChart:function(e){
    var index = e.currentTarget.dataset.index;
    var num = Number(e.currentTarget.dataset.num)
    
    var chartChose = this.data.chartChose;
    chartChose[index] = num;
    this.setData({
      chartChose: chartChose
    })
  }

})